#To be run in IronPython

import clr
from System import String
from System.IO import StreamReader, StreamWriter, DirectoryInfo, Path, File, FileInfo
from System.Text.RegularExpressions import Regex, RegexOptions

fLic = None
license = []
try:
    fLic = StreamReader('license.txt')
    while True:
	licLine = fLic.ReadLine()
	if licLine == None:
	    break
	license.append(licLine)
finally:
    if fLic:
	fLic.Close()

R = Regex('^(\S+)\s+.*Copyright.+reserved',
	  RegexOptions.IgnoreCase|RegexOptions.Compiled)

def processFile(fileIn,fileOut):
    fIn = None
    fOut = None
    changed = False
    try:
	fIn = StreamReader(fileIn)
	fOut = StreamWriter(fileOut)
	while True:
	    stuff = fIn.ReadLine()
	    if stuff == None:
		break
	    m = R.Match(stuff)
	    if m.Success and m.Groups.Count > 0:
		changed = True
		delim = m.Groups[1].Value
		for licLine in license:
		    fOut.Write(delim)
		    fOut.Write(' ')
		    fOut.WriteLine(licLine)
	    else:
		fOut.WriteLine(stuff)
    finally:
	if fIn:
	    fIn.Close()
	if fOut:
	    fOut.Close()
    return changed

def processDir(dir):
    di = DirectoryInfo(dir)
    numFiles = 0
    numModified = 0
    for f in di.GetFiles():
	lastWrite = f.LastWriteTime
	tempFile = Path.GetTempFileName()
	retVal = processFile(f.FullName,tempFile)
	if retVal:
	    numModified += 1
	    print f.FullName
	numFiles += 1
	File.Copy(tempFile,f.FullName,True)
	File.Delete(tempFile)
	fi = FileInfo(f.FullName)
	fi.LastWriteTime = lastWrite
    for d in di.GetDirectories():
	processDir(d.FullName)
    print numModified,'/',numFiles


	
